<template>
	<div>
		<p>正在登录中,请稍侯......</p>
	</div>
</template>

<script>
	import dingtalk from '../../js/DingtalkPC.js';
	import { dd_getconfig, dd_getuserinfo } from '../../api/api';
	import { Cookie } from '../../js/common';

	export default {
		name: 'auth',
		//props: ['href'],

		data() {
			return {
				//agentkey: "501001",
				platform: STATIC_CONFIG.platform,
				href: "home",
				msg: 'Welcome to Your Vue.js App',
				href:''
			}
		},
		methods: {

			loginFromDing: function() {
				
				console.log('auth from ding begin...');
				let _this = this;
				let token = Cookie.Get('token');
				// var myhref = this.href.toLowerCase() == "home"?"/#/home" : "/#/homeDD/" + this.href;
				let myhref = this.href;
//				if(this.href !== undefined){
//					myhref = this.href.path;
//				}
				
				if(token != "" && token != null) {
					window.location.href =  "/#/" + myhref;
					return;
				}
				
				//this.platform = STATIC_CONFIG.agentkey.substr(0,3);
				
				dd_getconfig(STATIC_CONFIG.agentkey).then(res => {
					var _config = res;
					//alert(this.agentkey);

					DingTalkPC.config({
						agentId: _config.agentId,
						corpId: _config.corpId,
						timeStamp: _config.timeStamp,
						nonceStr: _config.nonceStr,
						signature: _config.signature,
						jsApiList: ['runtime.info', 'biz.contact.choose',
							'device.notification.confirm', 'device.notification.alert',
							'device.notification.prompt', 'biz.ding.post',
							'biz.util.openLink'
						]
					});

					DingTalkPC.ready(function() {
					
						DingTalkPC.runtime.permission.requestAuthCode({
							corpId: _config.corpId,
							onSuccess: function(info) { //成功获得code值,code值在info中

							dd_getuserinfo(_this.platform + '|' + info.code).then(response => {
									if(response.errcode == 0) {
										console.log(response.name);
										
										Cookie.Set("token", response.token, 0);
										Cookie.Set("user_key", response.user_key, 0);
										Cookie.Set("user_name", response.name, 0);
										Cookie.Set("company_key", response.company_key, 0);
										Cookie.Set("company_name", response.company_name, 0);
										Cookie.Set("datasource", response.datasource, 0);
										
									 	
										window.location.href = "/#/" + myhref;

									} else {
										console.log('获取用户失败,请用钉钉打开此页面或刷新页面 ');
										alert("获取用户失败,请用钉钉打开此页面或刷新页面!");
									}

								});

							},
							onFail: function(err) { //获得code值失败

								console.log('fail: ' + JSON.stringify(err));
								alert('fail: ' + JSON.stringify(err));
							}
						});

						//console.log('point 3');

					});

					DingTalkPC.error(function(err) {
						console.log('error: ' + JSON.stringify(err));
						alert('dd error: ' + JSON.stringify(err));
					});
				})

			}

		},
		created: function() {
			//console.log('auth mounted begin...');
			this.loginFromDing();

		}
	}
</script>

<style>

</style>